package com.bookm.bookm.utils;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.db.Entity;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class EntityUtil {
    /**
     * 将 entity对象转换为指定实体类对象
     * @param obj 转换到的
     * @param data 实体类
     * @param <T> 类型
     * @return 类型
     */
    public static <T> T toObj(T obj, Entity data){
        Field[] fields = ReflectUtil.getFields(obj.getClass());
        Constructor<?> constructor = ReflectUtil.getConstructor(obj.getClass());
        T rst = null;
        try {
             rst = (T)constructor.newInstance();
        } catch (InstantiationException | InvocationTargetException | IllegalAccessException e) {
            e.printStackTrace();
        }
        for (Field field : fields) {
            String fieldName = field.getName();
            Class<?> fieldType = field.getType();
            String setName = "";
            String getName = StringUtil.humpToUnderline(fieldName);
            setName+="set"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1);
            Method methodByName = ReflectUtil.getMethodByName(rst.getClass(), setName);
            if(fieldType == String.class){
                try {
                    methodByName.invoke(rst, data.get(getName));
                } catch (IllegalAccessException | InvocationTargetException e) {
                    e.printStackTrace();
                }
            } else if(fieldType == Integer.class){
                try {
                    methodByName.invoke(rst, (Integer)data.get(getName));
                } catch (IllegalAccessException | InvocationTargetException e) {
                    e.printStackTrace();
                }
            } else if(fieldType == Date.class){
                try {
                    methodByName.invoke(rst, (Date)data.get(getName));
                } catch (IllegalAccessException | InvocationTargetException e) {
                    e.printStackTrace();
                }
            } else {
                System.out.println("没找到对应类型");
            }
        }

        return rst;
    }
    public static <T> List<T> toListObj(T obj, List<Entity> data){
        List<T> rst = new ArrayList<>();
        for (Entity datum : data) {
            T t = toObj(obj, datum);
            rst.add(t);
        }
        return rst;
    }
}
